<!--
 * @Description: 盘点单弹窗
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }">
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="4">
            <a-form-item label="仓库" name="warehouse_id">
              <Select name="Warehouse" :fetch-params="selectFetchParams.warehouse" v-model:value="form.warehouse_id" placeholder="请选择仓库" @change="onChangeWarehouse" />
            </a-form-item>
          </a-col>
          <template v-if="currentWarehouse.warehouse_type === 1">
            <a-col :span="4">
              <a-form-item label="经销商" name="dealer_id">
                <Select name="Dealer" v-model:value="form.dealer_id" placeholder="请选择经销商" @change="onChangeDealer" />
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-card>
      <a-card title="盘点明细" class="smart-margin-bottom10">
        <a-table size="small" :dataSource="tableData" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false">
          <template #bodyCell="{ text, record, column, index }">
            <template v-if="column.dataIndex === 'index'">
              <div class="form-table-index">
                <span>{{ index + 1 }}</span>
                <div class="form-table-index-btn-wrap">
                  <div class="form-table-index-btn">
                    <div class="form-table-index-btn-item" @click="addFormDetail(index)">+</div>
                    <div class="form-table-index-btn-item" @click="delFormDetail(index)">-</div>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'goods_name'">
              <a-input :value="text" readonly placeholder="请输入商品名称" size="small">
                <template #suffix>
                  <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                </template>
              </a-input>
            </template>
            <template v-if="column.dataIndex === 'img'">
              <a-image :width="text ? 30 : 50" :src="record.goods_name ? text || failImg : ''" />
            </template>
            <template v-if="column.dataIndex === 'spec_name'">
              <span v-if="record?.spec">{{ _.find(record.spec, { unit_type: record.default_unit_type }).spec_name }}</span>
            </template>
            <template v-if="column.dataIndex === 'barcode'">
              <span v-if="record?.spec">{{ _.find(record.spec, { unit_type: record.default_unit_type }).barcode }}</span>
            </template>
            <!-- <template v-if="column.dataIndex === 'spec_stock'">
              <span v-if="record?.spec">{{ _.find(record.spec, { unit_type: record.default_unit_type }).availableQuantities }}</span>
            </template> -->
            <template v-if="column.dataIndex === 'sale_price'">
              <span v-if="record?.spec">{{ _.find(record.spec, { unit_type: record.default_unit_type }).sale_price }}</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-form>
    <GoodsSelectModal ref="GoodsSelectModalRef" :default-selected-keys="_.map(tableData, 'id')" @confirm="onSelectGoods" />
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import Select from '@/components/business/select/index.vue'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import GoodsSelectModal from './goods-select-modal.vue'
import { checkStockApi } from '@/api/business/storage/stocktaking-api'
import failImg from '@/assets/images/notice/failImg.png'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])
const tableData = ref<any[]>([])
// 组件ref
const formRef = ref()

const formDefault = {
  // 仓库
  warehouse_id: '',
  // 经销商
  dealer_id: '',
  // 已选择的商品ID
  goods_ids: ''
}

const form = ref(_.cloneDeep(formDefault))

const rules = {
  warehouse_id: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
  dealer_id: [{ required: true, message: '请选择经销商', trigger: 'blur' }]
}

// 仓库
const currentWarehouse = ref<any>({})
function onChangeWarehouse(_: number, item: any) {
  if (item) {
    currentWarehouse.value = item
    tableData.value = []
    tableData.value.push({})
  } else {
    currentWarehouse.value = ''
  }
}

function onChangeDealer(val) {
  if (val) {
    tableData.value = []
    tableData.value.push({})
  }
}

// Select组件查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.EXPIRED.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询']
    },
    fields: 'id,name,warehouse_type'
  },
  dealer: {
    fields: 'id,name'
  }
}

// 商品选择
const GoodsSelectModalRef = ref()
const modalIndex = ref(0)
// 记录点击多选按钮的表格行索引，插入数据时使用
function showGoodsSelectModal(index: number) {
  if (!form.value.warehouse_id) {
    message.error('请选择仓库')
    return
  }
  if (currentWarehouse.value.warehouse_type === 1 && form.value.dealer_id === '') {
    message.error('请选择经销商')
    return
  }
  modalIndex.value = index
  GoodsSelectModalRef.value.showModal({ warehouse_id: form.value.warehouse_id, dealer_id: form.value.dealer_id })
}
function onSelectGoods(goodsList) {
  // 商品去重
  const sourceData = _.cloneDeep(tableData.value).filter((item) => item.id)
  if (sourceData.length === 0) {
    tableData.value = goodsList
  } else {
    const list = new Map(_.map(sourceData, (item) => [item.id, item]))
    goodsList.forEach((item) => {
      if (!list.has(item.id)) {
        list.set(item.id, item)
      }
    })
    tableData.value = Array.from(list.values())
  }
  // 自动追加一个空行
  if (!_.isEmpty(_.last(tableData.value))) tableData.value.push({})
}

// ----------------------------------  商品信息  ----------------------------------
// 表头配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: 260
  },
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  {
    title: '规格条码',
    dataIndex: 'barcode'
  },
  {
    title: '库存',
    dataIndex: 'totalAvailableQuantities'
  },
  {
    title: '单价',
    dataIndex: 'sale_price'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  }
]

// 增加空行
function addFormDetail(index: number) {
  tableData.value.splice(index + 1, 0, {})
}
// 删除行
function delFormDetail(index: number) {
  if (tableData.value.length === 1) return
  tableData.value.splice(index, 1)
}

// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ..._.keys(formDefault)])
  }
  tableData.value = [{}]
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  tableData.value = []
  visible.value = false
}

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      form.value.goods_ids = tableData.value
        .filter((item) => item?.id)
        .map((item) => item.id)
        .join(',')
      try {
        if (unref(form).id) {
          // await dealerApi.update(unref(form));
        } else {
          await checkStockApi.create(unref(form))
        }
        message.success('操作成功')
        onClose()
        emit('reload-list')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新建'))
</script>
<style scoped lang="less">
.form-table-item {
  margin-bottom: 0;
  max-width: 200px;
}
.form-table-index {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  .form-table-index-btn-wrap {
    display: none;
  }
  .form-table-index-btn {
    display: flex;
  }
  .form-table-index-btn-item {
    width: 50%;
    height: 100%;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .form-table-index-btn-item:hover {
    background: #f87171ff;
    color: white;
  }
}
.form-table-index:hover span {
  display: none;
}
.form-table-index:hover .form-table-index-btn-wrap {
  display: block;
}
</style>
